package cn.gbase.jiangsu.data.transfer.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.Product;
import cn.gbase.jiangsu.data.transfer.bean.ProductSellField;
import cn.gbase.jiangsu.data.transfer.bean.ProductSortTreeNode;
import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.bean.SupplierUser;
import cn.gbase.jiangsu.data.transfer.common.Constants;

@IocBean(args = { "refer:dao" })
public class ProductService extends IdEntityService<Product> {

	@Inject
	private ProductSortTreeNodeService productSortTreeNodeService;
	private final SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public ProductService() {
		super();
	}

	public ProductService(Dao dao) {
		super(dao);
	}

	/**
	 * 预订商品下架
	 */
	public void reverseShopDown() {
		String endDate = sfd.format(new Date());

		String sql = "select * from product where reserve_flag=1 and up_status=0 and reserve_end_date< '" + endDate
				+ "'";
		//					+ "' and order_type=" + Constants.PRODUCT_ORDER;
		SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
		Entity<Product> entity = dao().getEntity(Product.class);
		List<Product> list = sqlTemplate.query(sql, null, entity);
		for (Product product : list) {
			product.setUpStatus(1);
		}
		this.dao().update(list);

	}

	/**
	 * 定时收单
	 */
	//	public void reverseOrderReady() {
	//		String endDate = sfd.format(new Date());
	//
	//		String sql = "select * from goods_order where status=" + Constants.ORDER_STATUS_PAID + " and show_flag="
	//				+ Constants.ORDER_STATUS_PAID + " and create_time< '" + endDate + "'";
	//		//					+ "' and order_type=" + Constants.PRODUCT_ORDER;
	//		SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
	//		Entity<ProductOrder> entity = dao().getEntity(ProductOrder.class);
	//		List<ProductOrder> list = sqlTemplate.query(sql, null, entity);
	//		for (ProductOrder order : list) {
	//			order.setStatus(Constants.ORDER_STATUS_READY);
	//		}
	//		this.dao().update(list);
	//	}

	/**
	 * 按条件检索商品.
	 * 
	 * @param pageNumber
	 * @param keyword
	 * @return
	 */
	public QueryResult getProductList(int pageNumber, String productCode, String keyword, String nodeId,
			String passStatus, String upStatus, String reserveFlag, String supplierId, String virtualFlag,
			String orderByType, String columnInput) {

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);
		group = group.and("deleteFlag", "=", 0);
		// id
		if (productCode != null && productCode.length() > 0) {
			group = group.and("productCode", "like", "%" + productCode + "%");
		}

		// 关键词
		if (keyword != null && keyword.length() > 0) {
			// keyword = new String(keyword.getBytes("ISO-8859-1"), "UTF-8");
			group = group.and("productName", "like", "%" + keyword + "%");
		}

		// 所属分类
		if (nodeId != null && nodeId.length() > 0) {
			int selectNodeId = Integer.valueOf(nodeId);
			String idStr = productSortTreeNodeService.getDescendantNodeIdStr(selectNodeId);
			group = group.and("productSort", "in", idStr);
		}

		if (virtualFlag != null && virtualFlag.length() > 0) {
			group = group.and("virtualFlag", "=", Integer.valueOf(virtualFlag));
		}

		if (passStatus != null && passStatus.length() > 0) {
			group = group.and("passStatus", "=", Integer.valueOf(passStatus));
		}

		if (upStatus != null && upStatus.length() > 0) {
			group = group.and("upStatus", "=", Integer.valueOf(upStatus));
		}
		if (reserveFlag != null && reserveFlag.length() > 0) {
			group = group.and("reserveFlag", "=", Integer.valueOf(reserveFlag));
		}
		// 供应商ID
		if (supplierId != null && supplierId.length() > 0) {
			group = group.and("supplierId", "=", Integer.valueOf(supplierId));
		}

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(Product.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<Product>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		Condition condition = null;
		if (null == columnInput || columnInput.equals("")) {
			condition = Cnd.where(group).desc("id");
		} else {
			if (orderByType.equals("desc")) {
				condition = Cnd.where(group).desc(columnInput);
			} else {
				condition = Cnd.where(group).asc(columnInput);
			}
		}

		// 查询
		//List<Product> resultList = this.dao().query(Product.class, Cnd.where(group).desc("id"), pager); // 当前页面显示记录
		List<Product> resultList = this.dao().query(Product.class, condition, pager); // 当前页面显示记录
		// 返回
		return new QueryResult(resultList, pager);

	}

	/**
	 * 按条件检索多个供应商的商品.
	 * 
	 * @param pageNumber
	 * @param keyword
	 * @return
	 */
	public QueryResult getProductList(int pageNumber, String id, String keyword, String nodeId, String passStatus,
			List<Integer> supplier) {

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);

		// id
		if (id != null && id.length() > 0) {
			group = group.and("id", "=", Integer.valueOf(id));
		}

		// 关键词
		if (keyword != null && keyword.length() > 0) {
			// keyword = new String(keyword.getBytes("ISO-8859-1"), "UTF-8");
			group = group.and("productName", "like", "%" + keyword + "%");
		}

		// 所属分类
		if (nodeId != null && nodeId.length() > 0) {
			int selectNodeId = Integer.valueOf(nodeId);
			String idStr = productSortTreeNodeService.getDescendantNodeIdStr(selectNodeId);
			group = group.and("productSort", "in", idStr);
		}

		if (passStatus != null && passStatus.length() > 0) {
			group = group.and("up_status", "=", Integer.valueOf(passStatus));
		}

		// 供应商ID
		if (supplier != null && supplier.size() > 0) {
			group = group.and("supplierId", "in", supplier);
		}

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(Product.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<Product>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<Product> resultList = this.dao().query(Product.class, Cnd.where(group).desc("id"), pager); // 当前页面显示记录

		// 返回
		return new QueryResult(resultList, pager);

	}

	/**
	 * 根据ID取得商品.
	 * 
	 * @param id
	 * @return
	 */
	public Product getProductById(int id) {
		return this.dao().fetch(Product.class, id);
	}

	/**
	 * 根据ID取得供货商.
	 * 
	 * @param id
	 * @return
	 */
	public Supplier getSupplierById(int id) {
		return this.dao().fetch(Supplier.class, id);
	}

	/**
	 * 生成单树的JSON数据，ZTree格式.
	 * 
	 * @param treeId
	 *            树ID
	 * @return JSON变量的数据
	 */
	public String getTreeJsonDataForZTree(int treeId) {
		StringBuilder builder = new StringBuilder();
		builder.append("[");
		addOneTreeChildren(treeId, builder);
		builder.append("]");

		// [{id:1,pid:-1,name:'xx'},{id:2,pid:1,name:'yy'}]
		return builder.toString();
	}

	private void addOneTreeChildren(int treeId, StringBuilder builder) {

		// pid=0的也检索出来，作为根节点
		List<ProductSortTreeNode> nodeList = this.dao().query(ProductSortTreeNode.class, Cnd.wrap("treeId=" + treeId));
		for (ProductSortTreeNode treeNode : nodeList) {
			if (treeNode.getPid() == 0) {
				builder.append("{id:");
				builder.append(treeNode.getId());
				builder.append(",pId:0"); // 固定0
				builder.append(",name:'");
				builder.append("商品分类"); // 树的名字
				builder.append("'}");
			} else {
				builder.append("{id:");
				builder.append(treeNode.getId());
				builder.append(",pId:");
				builder.append(treeNode.getPid());
				builder.append(",name:'");
				builder.append(treeNode.getName());
				builder.append("'}");
			}
			builder.append(",");
		}
		if (nodeList.size() > 0) {
			builder.deleteCharAt(builder.length() - 1);
		}
	}

	/**
	 * 更新商品信息.
	 * 
	 * @param product
	 */
	public void updateProduct(Product p) {
		Product dbProduct = getProductById(p.getId());
		if (dbProduct == null) {
			return;
		}
		dbProduct.setProductCode(p.getProductCode());
		dbProduct.setProductName(p.getProductName());
		dbProduct.setStockNumber(p.getStockNumber());
		dbProduct.setSupplierPrice(p.getSupplierPrice());
		dbProduct.setProductSort(p.getProductSort());
		dbProduct.setProductContent(p.getProductContent());
		dbProduct.setAddPercent(p.getAddPercent());
		dbProduct.setSellPrice(p.getSellPrice());
		dbProduct.setSharePercent(p.getSharePercent());
		dbProduct.setRemark(p.getRemark());
		dbProduct.setRecommendFlag(p.getRecommendFlag());
		dbProduct.setSpecialPriceFlag(p.getSpecialPriceFlag());

		this.dao().update(dbProduct);
	}

	/**
	 * 更新商品信息.
	 * 
	 * @param product
	 */
	public void updateOrSaveProduct(Product p, SupplierUser u, String idNew) {
		Product dbProduct = getProductById(p.getId());
		if (dbProduct == null) {
			saveProduct(p, u, idNew);
		} else {
			dbProduct.setProductName(p.getProductName());
			dbProduct.setProductPic1(p.getProductPic1());
			dbProduct.setProductPic2(p.getProductPic2());
			dbProduct.setProductPic3(p.getProductPic3());
			dbProduct.setProductPic4(p.getProductPic4());
			dbProduct.setProductPic5(p.getProductPic5());
			dbProduct.setStockNumber(p.getStockNumber());
			dbProduct.setOriginalPrice(p.getOriginalPrice());
			dbProduct.setSupplierPrice(p.getSupplierPrice());
			dbProduct.setProductSort(p.getProductSort());
			dbProduct.setWeight(p.getWeight());
			dbProduct.setPassStatus(p.getPassStatus());
			dbProduct.setWeightUnit(p.getWeightUnit());
			dbProduct.setQuality(p.getQuality());
			dbProduct.setProductContent(p.getProductContent());
			dbProduct.setAddPercent(p.getAddPercent());
			dbProduct.setSellPrice(p.getSellPrice());
			dbProduct.setSharePercent(p.getSharePercent());
			dbProduct.setRemark(p.getRemark());
			dbProduct.setRecommendFlag(p.getRecommendFlag());
			dbProduct.setSpecialPriceFlag(p.getSpecialPriceFlag());
			dbProduct.setProductPlace(p.getProductPlace());
			dbProduct.setProductType(1);
			dbProduct.setVirtualFlag(p.getVirtualFlag());
			dbProduct.setReserveFlag(p.getReserveFlag());
			dbProduct.setReserveDate(p.getReserveDate());
			dbProduct.setReserveStartDate(p.getReserveStartDate());
			dbProduct.setReserveEndDate(p.getReserveEndDate());
			this.dao().update(dbProduct);
			//自定义属性
			if (p.getFieldList() != null && p.getFieldList().size() > 0) {
				List<ProductSellField> productSellField = getProductSellField(dbProduct.getId());
				this.dao().delete(productSellField);
				List<ProductSellField> fieldList = p.getFieldList();
				for (ProductSellField field : fieldList) {
					field.setProductId(dbProduct.getId());
				}
				this.dao().insert(fieldList);
			} else {
				List<ProductSellField> productSellField = getProductSellField(dbProduct.getId());
				this.dao().delete(productSellField);
			}
		}
	}

	public List<ProductSellField> getProductSellField(Integer id) {
		List<ProductSellField> query = this.dao().query(ProductSellField.class, Cnd.where("productId", "=", id));
		return query;
	}

	/**
	 * 取得下一个供应商编码（逻辑删除的也算在内，编码永不重复）.
	 */
	public String getNextSupplierCode(Integer sid) {

		// 自定义查询
		String sqlStr = "select max(product_code) from product where supplier_id=" + sid;
		Sql sql = Sqls.create(sqlStr);
		sql.setCallback(Sqls.callback.str());
		this.dao().execute(sql);
		String maxCode = sql.getString();

		// 为空，说明是第一个供应商
		if (maxCode == null || !(maxCode.length() > 0)) {
			return "000001";
		}

		// 加1返回，四位编码
		int iMaxCode = Integer.valueOf(maxCode);
		iMaxCode++;
		return ("000000" + iMaxCode).substring(("" + iMaxCode).length());
	}

	public void saveProduct(Product p, SupplierUser u, String idNew) {
		if (p.getProductName() != null && !"".equals(p.getProductName())) {
			Supplier supplier = this.dao().fetch(Supplier.class, u.getSupplierId());
			String code = getNextSupplierCode(u.getSupplierId());
			Product dbProduct = new Product();
			dbProduct.setAddtime(new Date());
			dbProduct.setSupplierId(u.getSupplierId());
			dbProduct.setPassStatus(0);
			dbProduct.setUpStatus(0);
			dbProduct.setProductPic1(p.getProductPic1());
			dbProduct.setProductPic2(p.getProductPic2());
			dbProduct.setProductPic3(p.getProductPic3());
			dbProduct.setProductPic4(p.getProductPic4());
			dbProduct.setProductPic5(p.getProductPic5());
			dbProduct.setCreateUser(u.getUsername());
			dbProduct.setProductCode(supplier.getSupplierCode() + "" + code);
			dbProduct.setProductName(p.getProductName());
			dbProduct.setStockNumber(p.getStockNumber());
			dbProduct.setWeight(p.getWeight());
			dbProduct.setWeightUnit(p.getWeightUnit());
			dbProduct.setQuality(p.getQuality());
			dbProduct.setSupplierPrice(p.getSupplierPrice());
			dbProduct.setOriginalPrice(p.getOriginalPrice());
			dbProduct.setProductSort(p.getProductSort());
			dbProduct.setProductContent(p.getProductContent());
			dbProduct.setAddPercent(p.getAddPercent());
			dbProduct.setSellPrice(p.getSellPrice());
			dbProduct.setSharePercent(p.getSharePercent());
			dbProduct.setRemark(p.getRemark());
			dbProduct.setRecommendFlag(p.getRecommendFlag());
			dbProduct.setSpecialPriceFlag(p.getSpecialPriceFlag());
			dbProduct.setProductPlace(p.getProductPlace());
			dbProduct.setProductType(1);
			dbProduct.setVirtualFlag(p.getVirtualFlag());
			dbProduct.setReserveFlag(p.getReserveFlag());
			dbProduct.setReserveDate(p.getReserveDate());
			dbProduct.setReserveStartDate(p.getReserveStartDate());
			dbProduct.setReserveEndDate(p.getReserveEndDate());
			this.dao().insert(dbProduct);
			//自定义属性
			if (p.getFieldList() != null && p.getFieldList().size() > 0) {
				List<ProductSellField> fieldList = p.getFieldList();
				for (ProductSellField field : fieldList) {
					field.setProductId(dbProduct.getId());
				}
				this.dao().insert(fieldList);
			} else {
				List<ProductSellField> productSellField = getProductSellField(dbProduct.getId());
				this.dao().delete(productSellField);
			}
			Sql sql = Sqls.create("update t_file set ywid = @ywid where ywid = @idNew");
			sql.params().set("ywid", dbProduct.getId());
			sql.params().set("idNew", idNew);
			this.dao().execute(sql);
		}
	}

	/**
	 * 审核通过商品.
	 * 
	 * @param id
	 *            商品ID
	 */
	public void passProduct(int id) {
		this.dao().update(Product.class, Chain.make("passStatus", 1), Cnd.where("id", "=", id));
	}

	/**
	 * 上架，下架.
	 * 
	 * @param id
	 *            商品ID
	 */
	public void upProduct(int id, int status) {
		if (status == 0)
			this.dao().update(Product.class, Chain.make("upStatus", status).add("passStatus", 0),
					Cnd.where("id", "=", id));
		else
			this.dao().update(Product.class, Chain.make("upStatus", status), Cnd.where("id", "=", id));
	}

	/**
	 * 删除商品.
	 * 
	 * @param id
	 *            商品ID
	 */
	public void deleteProduct(int id) {
		this.dao().update(Product.class, Chain.make("deleteFlag", 1), Cnd.where("id", "=", id));
	}

	public void updateProductCdxx(int id, String cdxx) {
		Sql sql = Sqls.create("update product set product_place = @productPlace where id = @id");
		sql.params().set("productPlace", cdxx);
		sql.params().set("id", id);
		this.dao().execute(sql);
	}
}
